import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserService } from '../../user/user.service';

/**
 *
 * 用途：验证JWT Token，提取用户信息
 *
 * 原理：
 * 1. 从请求头中提取Token（Authorization: Bearer xxx）
 * 2. 验证Token签名和有效期
 * 3. 调用validate方法，返回用户信息
 * 4. 将用户信息挂载到request.user
 *
 */

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly userService: UserService,
    private readonly configService: ConfigService,
  ) {
    super({
      // 从请求头的Authorization字段提取Token
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false, // 不忽略过期Token
      secretOrKey: configService.get('JWT_SECRET') as string, // JWT密钥
    });
  }
  /**
   * 验证Token payload
   *
   * @param payload JWT解码后的payload
   * @returns 用户信息（会挂载到request.user）
   */
  async validate(payload: any) {
    // payload结构：{ sub: userId, username, email, membershipLevel }
    const user = await this.userService.findById(payload.sub);

    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }

    if (user.status !== 'active') {
      throw new UnauthorizedException('账号已被封禁或未激活');
    }

    // 返回的数据会挂载到 request.user
    return {
      id: user.id,
      username: user.username,
      email: user.email,
      membershipLevel: user.membershipLevel,
      role: user.role,
    };
  }
}
